<template>
    <!-- 表单模糊查询 -->
    <div class="form-container">
    <el-form :model="queryForm" class="flex-form">
      <el-form-item label="标题名" class="form-item">
        <el-input v-model="queryForm.title" placeholder="请输入要查询的标题" type="text" @blur="getAll()" />
      </el-form-item>

      <el-form-item class="form-buttons">
        <el-button  type="warning" round @click="cleanCondition()">重置</el-button>
        <el-button type="success" @click="addCarouseButton()">添加轮播图</el-button>
      </el-form-item>
    </el-form>
  </div>
            <!-- <el-form-item label="实名状态">
            <el-radio-group v-model="queryForm.isAuthentication">
                <el-radio label="1" value="1" @change="getAll()">已实名</el-radio>
                <el-radio label="2" value="2" @change="getAll()">未实名</el-radio>
                <el-button link type="danger" @click="cleanCondition()">重置查询条件</el-button>
            </el-radio-group>
        </el-form-item> -->
<!--  轮播图 -->
    <el-table :data="tableData"  style="width: 100%" :default-sort="{ prop: 'date', order: 'descending' }">
        <el-table-column label="序号"  type="index" />
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="content" label="内容" />
        <el-table-column prop="position" label="轮播图位置" />
        <el-table-column prop="createTime" label="创建时间" sortable />
        <!-- <el-table-column prop="administratorImage" label="头像" /> -->
        <el-table-column prop="imageUrl" label="图片" #default="scope">
            <el-image :src="scope.row.imageUrl" style="width: 60px; height: 60px" />
        </el-table-column>

        <!-- <el-table-column prop="isAuthentication" label="Zip" #default="scope">
            <span v-if="scope.row.isAuthentication == 1" style="color: green;">已实名</span>
            <span v-if="scope.row.isAuthentication == 2" style="color: red;">未实名</span>
        </el-table-column> -->
        <el-table-column label="操作">
            <template #default="scope">
                <el-button size="small" type="primary" @click="handleEdit(scope.row)">
                    修改
                </el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <div class="demo-pagination-block">
        <el-pagination v-model:current-page="queryForm.pageNum" v-model:page-size="queryForm.pageSize"
            :page-sizes="[5, 10, 20, 50]" :size="size" :disabled="disabled" :background="background"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </div>
    
    <el-dialog v-model="dialogVisible" title="添加轮播图" width="600">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="addArticleForm"  :rules="rules"
            label-width="auto" class="demo-ruleForm">
            <el-form-item label="标题" prop="title">
                <el-input  v-model="addArticleForm.title"/>
            </el-form-item>
            <el-form-item label="内容" prop="content">
                <el-input v-model="addArticleForm.content"  />
            </el-form-item>
            <el-form-item label="图片位置" prop="position">
                <el-input v-model="addArticleForm.position" type="number" />
            </el-form-item>


            <el-form-item label="图片">
                <el-upload class="avatar-uploader" action="/api/admin/user/upload" :show-file-list="false"
                    :headers="{ 'token': token }" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>

            <el-button type="success" @click="submitBUtton()">
                提交
            </el-button>

        </el-form>
    </el-dialog>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { CarouselimageList, CarouselimageDelete, CarouselimageAddOrUpdate } from '../../api/carousel/index.js'

import { useRouter } from "vue-router";
import { userUserStore } from '../../store/userStore.js'
import { ElMessage } from "element-plus";
import { ElLoading } from 'element-plus';
// 封装一个方法，用于显示加载效果
function showLoading() {
    return ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
    });
}
const userStore = userUserStore()
const router = useRouter()
const tableData = ref([])
const queryForm = ref({
    pageNum: 1,
    pageSize: 5,

})
const total = ref()
const token = ref(localStorage.getItem("token"))

//图片
const imageUrl = ref('')
const formRef = ref()
const handleAvatarSuccess = (
    response,
    uploadFile
) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw)
    addArticleForm.value.imageUrl = response.msg
    console.log(response);
}
//验证的函数
const beforeAvatarUpload = (rawFile) => {
    const isImage = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png' || rawFile.type === 'image/jpg';
    if (!isImage) {
        ElMessage.error('Avatar picture must be in JPG, PNG, or JPEG format!');
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size cannot exceed 2MB!');
        return false;
    }
    return true;
};

const user = JSON.parse(localStorage.getItem("user"))
console.log(user.administratorName);


const ruleFormRef = ref()
const addArticleForm = ref({
    // createBy: user.administratorName
})

let dialogVisible = ref(false)
const handleSizeChange = (val) => {
    queryForm.value.pageSize = val
    getAll()
}
const handleCurrentChange = (val) => {
    queryForm.value.pageNum = val
    getAll()
}

const handleEdit = (row) => {
    imageUrl.value = row.imageUrl
    dialogVisible.value = true
    addArticleForm.value = row
    addArticleForm.value.updateBy = user.administratorName
}
const addCarouseButton = () => {
    imageUrl.value = ''
    addArticleForm.value = {}
    dialogVisible.value = true
}
const handleDelete = (row) => {
    console.log(row)
    CarouselimageDelete(row).then(res => {
        if (res.data.code == 200) {
            ElMessage.success(res.data.msg)
            getAll()
        } else {
            ElMessage.error(res.data.msg)
            getAll()
        }
    })
}

function getAll() {
    const loadingInstance = showLoading(); // 显示加载效果
    CarouselimageList(queryForm.value).then(res => {
        setTimeout(() => {
                // 异步操作完成后，关闭加载效果
                loadingInstance.close();
            }, 300);
        console.log(res.data.data);
        if (res.data.code == 200) {
            tableData.value = res.data.data
            total.value = res.data.total
        } else {
            ElMessage.error(res.data.msg)
            router.push('/')
        }
    })
}

function submitBUtton() {
    console.log(addArticleForm);
     ruleFormRef.value.validate((valid) => {
         if (valid) {
            CarouselimageAddOrUpdate(addArticleForm.value).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success("操作成功！")
                    getAll()
                    dialogVisible.value = false
                } else {
                    ElMessage.error("操作失败！")
                    dialogVisible.value = false
                }
            })
        }
     })
}

function cleanCondition() {
    queryForm.value.title = '',
        getAll()
}



onMounted(() => {
    getAll()
})


const rules = reactive({
    title: [
        { required: true, message: '标题不可为空', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '内容不可为空', trigger: 'blur' },
    ],
    position: [
        { required: true, message: '图片位置不可为空', trigger: 'blur' },
    ],

})

</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
.form-container {
  display: flex;
  justify-content: center; /* Center the form container */
}

.flex-form {
  display: flex;
  align-items: center; /* Vertically center items */
  gap: 10px; /* Optional spacing between items */
}

.form-item {
  margin-right: 10px; /* Spacing between form items */
}

.form-buttons {
  display: flex;
  gap: 10px; /* Spacing between buttons */
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>